<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>pre代码复制功能</title>
    <script src="jquery.min.js"></script>
    <style>
        .content{
            width: 1000px;
            margin: 10px auto;
        }
        .content pre{
            position: relative;
            background-color: #f5f5f5;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 10px;
        }
        pre .btn-pre-copy{
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            -khtml-user-select: none;
            user-select: none;
            position: absolute;
            top: 10px;
            right: 12px;
            font-size: 12px;
            line-height: 1;
            cursor: pointer;
            color: hsla(0,0%,54.9%,.8);
            transition: color .1s;
        }
        textarea{
            width: 100%;
        }
    </style>
</head>

<body>
<div class="content">
    <pre>@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}</pre>
    ---分割线---
    <pre>@RestController
@RequestMapping("/")
public class TestController {

    @GetMapping("/test")
    public String test() {
        return "test";
    }

}</pre>
    ---分割线---
    <pre>server:
  port: 8080</pre>
    ---复制粘贴测试区域---<br>
    <textarea rows="10" onclick="selectAll(this)">你可以在这里进行粘贴测试</textarea>
</div>
<script>
    $(function(){
        //给每一串代码元素增加复制代码节点
        let preList = $(".content pre");
        for (let pre of preList) {
            //给每个代码块增加上“复制代码”按钮
            let btn = $("<span class=\"btn-pre-copy\" onclick='preCopy(this)'>复制代码</span>");
            btn.prependTo(pre);
        }
    });

    /**
     * 执行复制代码操作
     * @param obj
     */
    function preCopy(obj) {
        //执行复制
        let btn = $(obj);
        let pre = btn.parent();
        //为了实现复制功能。新增一个临时的textarea节点。使用他来复制内容
        let temp = $("<textarea></textarea>");
        //避免复制内容时把按钮文字也复制进去。先临时置空
        btn.text("");
        temp.text(pre.text());
        temp.appendTo(pre);
        temp.select();
        document.execCommand("Copy");
        temp.remove();
        //修改按钮名
        btn.text("复制成功");
        //一定时间后吧按钮名改回来
        setTimeout(()=> {
            btn.text("复制代码");
        },1500);
    }

    /**
     * 全选文本
     * @param obj
     */
    function selectAll(obj){
        $(obj).select();
    }
</script>
</body>
</html>